<template>
  <div class="container">
    <div class="search">
      <el-form :inline="true"  label-width="68px" size="small">
         <el-form-item label="角色名">
            <el-input v-model="searchData.name" placeholder="角色名"></el-input>
         </el-form-item>
         <el-form-item label="描述">
            <el-input v-model="searchData.description" placeholder="描述"></el-input>
         </el-form-item>
         <!-- <el-form-item label="审批人">
         <el-button type="primary">添加角色</el-button>
         </el-form-item> -->
      </el-form>
    </div>
    <div class="operation">
       <el-button type="primary" @click="search">搜索</el-button>
       <el-button type="primary" @click="handleAddRole">添加</el-button>
    </div>
    <el-table :data="listData" style="width: 100%" :height="578">
      <el-table-column prop="name" label="角色名">
      </el-table-column>
      <el-table-column prop="description" label="介绍">
      </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditRole(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.pageNumber"
      :page-sizes="[10,20, 50, 100, 500]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total">
    </el-pagination>
    <el-dialog
      title="添加角色"
      :visible="dialog == 'addRole'" :before-close="handleAddClose"
      width="30%">
      <el-form :inline="true" :model="addData" :rules="roleRule" ref="addForm" label-width="68px" size="small" >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="addData.name" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addData.description" placeholder="描述"></el-input>
        </el-form-item>
        <el-form-item label="权限">
            <el-tree :data="permissions" ref="addTree" :props="defaultProps" node-key = "id" show-checkbox></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearAddData()">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="添加角色"
      :visible="dialog == 'editRole'" :before-close="handleEditClose"
      width="30%">
      <el-form :inline="true" :model="editData" :rules="roleRule" ref="editForm" label-width="68px" size="small" >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="editData.name" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editData.description" placeholder="描述"></el-input>
        </el-form-item>
        <el-form-item label="权限">
            <el-tree :data="permissions" ref="editTree" :props="defaultProps" node-key="id" show-checkbox></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearEditData()">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/config/server.js'
export default {
  data () {
    return {
      // page: 0,
      // size: 20,
      listData: [],
      permissions: null,
      searchData: {
        name: '',
        description: ''
      },
      addData: {
        name: '',
        description: '',
        permissions: []
      },
      editData: {
        name: '',
        description: '',
        permissions: []
      },
      dialog: '',
      page: {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
      },
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      roleRule: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getPermissions()
    this.search()
  },
  methods: {
    search () {
      api.roleList({
        page: this.page.pageNumber - 1,
        size: this.page.pageSize,
        name: this.searchData.name,
        description: this.searchData.description
      }).then((res) => {
        this.listData = res.result.content
        this.page.pageNumber = res.result.pageable.pageNumber + 1
        this.page.pageSize = res.result.pageable.pageSize
        this.page.total = res.result.totalElements
        this.page.totalPage = res.result.totalPages
      })
    },
    getPermissions () {
      api.permissionsList().then((res) => {
        this.permissions = res.result
      })
    },
    handleAddRole () {
      this.dialog = 'addRole'
    },
    addRole () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          let permissions = this.$refs.addTree.getCheckedNodes().map((item) => {
            return item.id
          })
          let halfpermissions = this.$refs.addTree.getHalfCheckedNodes().map((item) => {
            return item.id
          })
          api.addRole({
            name: this.addData.name,
            description: this.addData.description,
            permissions: [
              permissions,
              ...halfpermissions
            ]
          }).then((res) => {
            if (res.ret === 1) {
              this.$message('添加成功')
              this.clearAddData()
              this.dialog = ''
              this.search()
            } else {
              this.$message(res.msg)
            }
          })
        }
      })
    },
    clearAddData () {
      this.addData = {}
      this.$refs.addTree.setCheckedKeys([])
    },
    handleAddClose () {
      this.clearAddData()
      this.dialog = ''
    },
    handleEditRole (row) {
      this.dialog = 'editRole'
      api.rolePermissions(row.id).then((res) => {
        this.editData = {
          id: row.id,
          name: row.name,
          description: row.description
        }
        let ids = []
        this.appendChild(ids, res.result)
        this.$refs.editTree.setCheckedKeys(ids)
      })
    },
    editRole () {
      let permissions = this.$refs.editTree.getCheckedNodes().map((item) => {
        return item.id
      })
      let halfpermissions = this.$refs.editTree.getHalfCheckedNodes().map((item) => {
        return item.id
      })
      api.editRole({
        id: this.editData.id,
        name: this.editData.name,
        description: this.editData.description,
        permissions: [
          permissions,
          ...halfpermissions
        ]
      }).then((res) => {
        if (res.ret === 1) {
          this.$message('修改成功')
          this.clearEditData()
          this.dialog = ''
          this.search()
        } else {
          this.$message(res.msg)
        }
      })
    },
    handleEditClose () {
      this.clearEditData()
      this.dialog = ''
    },
    clearEditData () {
      this.editData = {
        name: '',
        description: '',
        permissions: []
      }
    },
    handleDeleteRole (row) {
      this.$confirm('确定删除角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteRole(row.id).then((res) => {
          if (res.ret === 1) {
            this.$message('删除成功')
            this.search()
          } else {
            this.$message(res.msg)
          }
        })
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })
    },
    appendChild (ids, result) {
      for (let i = 0; i < result.length; i++) {
        let permission = result[i]
        if (permission.parentId) {
          ids.push(permission.id)
        }
        if (permission.child) {
          this.appendChild(ids, permission.child)
        }
      }
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.search()
    },
    handleCurrentChange (val) {
      this.page.pageNumber = val
      this.search()
    },
    currentPage () {

    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 10px 0 0 0 ;
  }
  .search{
    .el-form{
      width:100%;
      display:flex;
      flex-direction:row;
      justify-content:flex-start;
      flex-wrap:wrap;
      .el-form-item{
        width: 270px;
      }
    }
    width:100%;
  }
  .operation{
    margin-top:10px;
    float: left;
  }
  .el-tree{
    width:200px;
  }
  // .el-input {
  //   width: 200px;
  // }

</style>>
